import React from 'react';
import _ from 'lodash';
import { Redirect, useModel, history } from 'umi';
import { getToken } from '@/utils/auth';
import { getOriginalPath } from '@/utils/routeFormat';

export default (props) => {
  const { initialState } = useModel('@@initialState');
  const { routePathList } = initialState;
  const authPathList = _.keys(routePathList || {});
  const currentPathName = getOriginalPath(history.location.pathname);

  if (getToken()) {
    if (_.includes(authPathList, currentPathName)) {
      return <>{props.children}</>;
    }
    return <Redirect to="/403" />;
  }
  return <Redirect to="/login" />;
};
